<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件
if (!function_exists('build_ranstr')) {
    /**
     * 获得随机字符串
     * @param $len             需要的长度
     * @param $special        是否需要特殊符号
     * @return string       返回随机字符串
     */
    function build_ranstr($len = 8, $special = false)
    {
        $chars = array(
            "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
            "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
            "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
            "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
            "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2",
            "3", "4", "5", "6", "7", "8", "9"
        );

        if ($special) {
            $chars = array_merge($chars, array(
                "!", "@", "#", "$", "?", "|", "{", "/", ":", ";",
                "%", "^", "&", "*", "(", ")", "-", "_", "[", "]",
                "}", "<", ">", "~", "+", "=", ",", "."
            ));
        }

        $charsLen = count($chars) - 1;
        shuffle($chars);                            //打乱数组顺序
        $str = '';
        for ($i = 0; $i < $len; $i++) {
            $str .= $chars[mt_rand(0, $charsLen)];    //随机取出一位
        }
        return $str;
    }
}

if (!function_exists('upload')) {
    /**
     * 上传图片
     * @param name 图片名
     * @param path 保存图片路径
     * @param size 图片大小
     * @param ext 图片格式
     * @return filename 返回上传后的图片名
     */
    function upload($name, $path = 'uploads', $size = 1048576, $ext = ['jpg', 'png', 'gif', 'jpeg'])
    {
        // 用助手函数去接收图片
        $file = request()->file($name);



        // 把\替换/
        $NewPath = str_replace('\\', '/', ROOT_PATH . 'public/' . $path);

        if ($file) {
            // 验证图片格式并且移动到指定目录
            $info = $file->validate(['size' => $size, 'ext' => $ext])->move($NewPath);

            if ($info) {
                // 获取保存的图片名
                $Savaname = $info->getSaveName();



                // 保存到数据库
                $filename = '/' . $path . '/' . $Savaname;
                $filename = str_replace('\\', '/', $filename);

                return $filename;
            }
        }

        return false;
    }
}

//创建一个公共函数，来处理评论的递归  处理数据
/**
 * @param list 评论数据
 * @param pid 评论上一级id
 * @param User 用户
 */
function CommentTree($list, $pid = 0, $User)
{
    // 定义空的数组
    $data = [];

    if ($list) {
        foreach ($list as $item) {

            if (!empty($item['like'])) {
                //字符串转数组
                $LikeArr = explode(',', $item['like']);
                $LikeArr = array_filter($LikeArr);  //去除数组中的空元素
                $LikeCount = is_array($LikeArr) ? count($LikeArr) : 0;

                // 自定义一个数据表不存在的字段
                $item['like_count'] = $LikeCount;

                //判断当前这一条评论是不是本人点过赞
                // $user['id']
                // $LikeArr
                // echo $User['id'];
                // halt($LikeArr);
                if (in_array($User['id'], $LikeArr)) {
                    // 点过赞
                    // echo 111;
                    // exit;
                    $item['active'] = true;
                } else {
                    // echo 11;
                    // exit;
                    $item['active'] = false;
                }
            } else {
                //当like字段为空
                $item['like_count'] = 0;
            }

            //id = 1 pid = 0
            if ($item['pid'] == $pid) {
                //找出相等pid值，给当前的评论新增一个自定义属性
                //递归找子集
                $item['child'] = CommentTree($list, $item['id'], $User);
                $data[] = $item;
            }
        }
    }

    return $data;
}

//处理递归循环输出  处理输出
/**
 * @param list 评论数据
 * @param post 当前帖子数据
 * @param flag 是否为父级评论
 * @return output 返回递归数据
 */
function CommentHtml($list, $post, $flag = 'top', $output = "")
{
    // $output = "";

    foreach ($list as $key => $item) {
        //外边距
        $PaddingLeft = $item['level'] * 1;

        $output .= "<li style='padding-left:{$PaddingLeft}em' class='jieda-daan'>";
        //头像
        $output .= "<div class='detail-about detail-about-reply'>";
        // 头像
        $url = url('home/user/index', ['userid' => $item['userid']]);
        $output .= "<a class='fly-avatar' href='$url'>";

        //判断头像
        if (is_file($item['user']['avatar'])) {
            $avatar = $item['user']['avatar'];
            $output .= "<img src='$avatar' />";
        } else {
            $output .= "<img src='/static/home/res/images/avatar/default.png' />";
        }
        $output .= "</a>";


        // 用户信息
        $output .= "<div class='fly-detail-user'>";
        $output .= "<a href='javascript:void(0)' class='fly-link'>";
        $nickname = $item['user']['nickname'];
        $output .= " <cite>$nickname</cite>";

        if ($item['user']['auth'] > 0) {
            $output .= "<i class='iconfont icon-renzheng'></i>";
        }
        $output .= "</a>";

        //楼主
        if ($key == 0 && $flag == 'top') {
            $output .= "<span style='color:#FF7200'>(楼主)</span>";
        }

        //判断是否为发帖人
        if ($item['userid'] == $post['userid']) {
            $output .= "<span style='color:#5FB878'>(发帖人)</span>";
        }
        $output .= "</div>";

        // 评论时间
        $output .= "<div class='detail-hits'>";
        $output .= "<span>{$item['createtime']}</span>";
        $output .= "</div>";


        // 采纳图标
        if ($item['accept'] == 1) {
            $output .= "<i class='iconfont icon-caina' title='最佳答案'></i>";
        }
        $output .= "</div>";

        // 评论内容
        $output .= "<div class='detail-body jieda-body photos'>";
        $output .= "<p>{$item['content']}</p>";
        $output .= "</div>";

        // 回复
        if (cookie('LoginUser')) {
            $output .= "<div class='jieda-reply'>";
            // 点赞
            if (isset($item['active'])) {
                $output .= "<span class='jieda-zan zanok' data-id='{$item['id']}' type='zan'>";
            } else {
                $output .= "<span class='jieda-zan' data-id='{$item['id']}' type='zan'>";
            }
            $output .= "<i class='iconfont icon-zan'></i>";
            $output .= "<em>{$item['like_count']}</em>";
            $output .= "</span>";

            // 回复
            if (!$post['accept']) {
                $pid = $item['id'];
                $nickname2 = $item['user']['nickname'];
                $output .= "<a href='#comment' class='reply' type='reply' data-pid='$pid' data-nickname='$nickname2'>";
                $output .= "<i class='iconfont icon-svgmoban53'></i>\r\n回复";
                $output .= "</a>";
            }
            $output .= "<div class='jieda-admin'>";
            // (登录的人 == 发帖userid)发帖人  || 评论本人（评论人 == 登录的人）

            $userid = cookie('LoginUser')['id'];
            if ($userid == $post['userid'] || $userid == $item['userid']) {
                if (!$post['accept']) {
                    $output .= " <span type='del' class='delcomment' data-pid='{$item['id']}'>删除</span>";
                }
            }

            if ($userid == $post['userid']) {
                if (!$post['accept']) {
                    $output .= "<span class='accept' data-comid='{$item['id']}' class='jieda-accept' type='accept'>";
                    $output .= "采纳";
                    $output .= "</span>";
                }
            }
            $output .= "</div>";


            $output .= "</div>";
        }
        $output .= "</li>";

        //判断是否有子集
        if (!empty($item['child'])) {
            $output = CommentHtml($item['child'], $post, 'son', $output);
        }
    }

    return $output;
}

//时间判断用靠近词语表示
function Tiemstr($creatime = NULL)
{

    $text = '';
    //获取当前与创建之间的时间差
    $time = time();
    //转换成时间戳
    $creatime = strtotime($creatime);
    $timecha = abs($time - $creatime);

    //判断时间戳
    switch ($timecha) {

        case $timecha < 60:
            $text = '刚刚'; // 一分钟内
            break;
        case $timecha < 60 * 60:
            $text = floor($timecha / 60) . '分钟前'; //一小时内
            break;
        case $timecha < 60 * 60 * 24:
            $text = floor($timecha / (60 * 60)) . '小时前'; // 一天内
            break;
        case $timecha < 60 * 60 * 24 * 3:
            $text = floor($creatime / (60 * 60 * 24)) == 1 ? '昨天 ' . date('H:i', $creatime) : '前天 ' . date('H:i', $creatime); //昨天和前天
            break;
        case $timecha < 60 * 60 * 24 * 30:
            $text = date('m月d日 H:i', $creatime); //一个月内
            break;
        case $timecha < 60 * 60 * 24 * 365:
            $text = date('m月d日', $creatime); //一年内
            break;
        default:
            $text = date('Y年m月d日', $creatime); //一年以前
            break;
    }

    // var_dump($text);
    // exit;

    return $text;
}


//签到时间判定，判定是否过来当天的零点
function signin($creatime)
{
    $time = time();
    $startiem = strtotime("+24 hours");
    $cha = strtotime(date('Y-m-d'));

    $date = "2019/12/01";
    //转换成时间戳

    $timestamp = strtotime($creatime);

    //上一天当天距离零点的时间戳
    $zeroto = strtotime(date('Y-m-d', $timestamp)) + 86400 - $timestamp;

    // 一天的时间戳86400
    //转化时间戳
    $creatime = strtotime($creatime);

    if (!(abs($time - $creatime) < abs($zeroto))) {

        //未签到
        return false;
    } else {
        //已经签到
        return true;
    }
}

//连续签到的次数的计算
function signilin($sinlist)
{
    $daystime = [];
    foreach ($sinlist as $key => $item) {
        $createtime = strtotime($item['createtime']);

        array_push($daystime, $createtime);
    }

    $i = 0;
    for (; $i < count($daystime); $i++) {
        if ($i == 0) {
            continue;
        } else if (!(abs($daystime[$i] - $daystime[$i - 1]) < 86400)) {

            break;
        }
    }
    // var_dump($i);
    // var_dump(abs($daystime[2]-$daystime[1]));
    // exit;

    return $i;
}

//评论数量
function commsun($items)
{


    $visit = trim($items);
    $VisitArr = explode(',', $visit); //转换为数组
    $VisitArr = array_filter($VisitArr);  //去除数组中的空元素
    $VisitCount = is_array($VisitArr) ? count($VisitArr) : 0;

    return $VisitCount;
}

//生成唯一订单号
if (!function_exists('build_code')) {

    /**
     * 生成唯一订单号
     *
     * @param string $path 指定的path
     * @return string
     */
    function build_code($prefix = "")
    {
        @date_default_timezone_set("PRC");
        $order_id_main = date('YmdHis') . rand(10000, 99999);
        //订单号码主体长度
        $order_id_len = strlen($order_id_main);
        $order_id_sum = 0;
        for ($i = 0; $i < $order_id_len; $i++) {
            $order_id_sum += (int)(substr($order_id_main, $i, 1));
        }
        //唯一订单号码（YYYYMMDDHHIISSNNNNNNNNCC）
        $osn = $prefix . $order_id_main . str_pad((100 - $order_id_sum % 100) % 100, 2, '0', STR_PAD_LEFT); //生成唯一订单号
        return $osn;
    }
}
?>